﻿using System;
using System.Collections.Generic;

namespace Server
{
    public class Chat : IChat
    {
        private static readonly List<string> _users = new List<string>();
        private static readonly List<Tuple<string, string>> Messages = new List<Tuple<string, string>>();

        public string ReverseString(string str)
        {
            var buf = str.ToCharArray();
            var idx = 0;
            for (var i = str.Length - 1; i >= 0; i--)
                buf[idx++] = str[i];

            return new string(buf);
        }


        public bool Join(string nickname)
        {
            if (_users.TrueForAll(us => us != nickname))
            {
                _users.Add(nickname);
                return true;
            }
            return false;
        }

        public void Disconnect(string nickname)
        {
            _users.Remove(nickname);
        }

        public void ReceiveMessage(string nickname, string message)
        {
            Messages.Add(new Tuple<string, string>(nickname, message));
        }

        public Tuple<int, List<Tuple<string, string>>> GetNewMessages(string nickname, int idLastMessage)
        {
            if (idLastMessage < 0)
                return new Tuple<int, List<Tuple<string, string>>>(Messages.Count, new List<Tuple<string, string>>());
            var msg = new List<Tuple<string, string>>();

            for (var i = idLastMessage; i < Messages.Count; ++i)
                msg.Add(Messages[i]);

            return new Tuple<int, List<Tuple<string, string>>>(Messages.Count, msg);
        }


        public List<string> Users()
        {
            return _users;
        }


        public bool Live()
        {
            return true;
        }
    }
}
